package com.wande.dataplatform.filecollection.source.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wande.common.core.exception.ServiceException;
import com.wande.dataplatform.filecollection.common.constant.FileCollectionConstants;
import com.wande.dataplatform.filecollection.common.utils.MinioUtils;
import com.wande.dataplatform.filecollection.source.IFileSource;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.StatObjectArgs;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 对象存储文件来源实现
 *
 * @author wande
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OssFileSource implements IFileSource {

    private final MinioUtils minioUtils;

    @Override
    public String getSupportedSourceType() {
        return FileCollectionConstants.SourceType.OSS;
    }

    @Override
    public List<String> listFiles(String config) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String bucketName = configJson.getStr("bucketName");
        String prefix = configJson.getStr("prefix", "");
        String pattern = configJson.getStr("pattern", "*");

        List<String> files = new ArrayList<>();
        try {
            MinioClient minioClient = minioUtils.getMinioClient();
            Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder()
                    .bucket(bucketName)
                    .prefix(prefix)
                    .build()
            );

            for (Result<Item> result : results) {
                Item item = result.get();
                if (!item.isDir() && matchPattern(item.objectName(), pattern)) {
                    files.add(item.objectName());
                }
            }
            log.info("列出OSS文件, bucket={}, prefix={}, count={}", bucketName, prefix, files.size());
        } catch (Exception e) {
            throw new ServiceException("列出OSS文件失败: " + e.getMessage());
        }
        return files;
    }

    @Override
    public InputStream getFileStream(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String bucketName = configJson.getStr("bucketName");

        try {
            return minioUtils.downloadFile(filePath);
        } catch (Exception e) {
            throw new ServiceException("下载OSS文件失败: " + filePath);
        }
    }

    @Override
    public long getFileSize(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String bucketName = configJson.getStr("bucketName");

        try {
            MinioClient minioClient = minioUtils.getMinioClient();
            return minioClient.statObject(
                StatObjectArgs.builder()
                    .bucket(bucketName)
                    .object(filePath)
                    .build()
            ).size();
        } catch (Exception e) {
            throw new ServiceException("获取OSS文件大小失败: " + filePath);
        }
    }

    @Override
    public boolean testConnection(String config) {
        try {
            JSONObject configJson = JSONUtil.parseObj(config);
            String bucketName = configJson.getStr("bucketName");
            MinioClient minioClient = minioUtils.getMinioClient();
            return minioClient.bucketExists(
                io.minio.BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build()
            );
        } catch (Exception e) {
            log.error("测试OSS连接失败", e);
            return false;
        }
    }

    private boolean matchPattern(String fileName, String pattern) {
        if ("*".equals(pattern)) {
            return true;
        }
        String regex = pattern.replace(".", "\\.").replace("*", ".*");
        return fileName.matches(regex);
    }
}
